package com.guangzhi.weijianzhi.mainhome;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.PopupWindow.OnDismissListener;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.guangzhi.weijianzhi.R;
import com.guangzhi.weijianzhi.activity.BaseActivity;
import com.guangzhi.weijianzhi.adapter.DialogAdapter;
import com.guangzhi.weijianzhi.adapter.SimpleBaseAdapter;
import com.guangzhi.weijianzhi.utils.ProvinceCity;
import com.guangzhi.weijianzhi.utils.ProvinceCity.ProvinceAndCity;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.umeng.analytics.MobclickAgent;

public class PositionListFindActivity extends BaseActivity implements OnClickListener, OnItemClickListener, OnRefreshListener2<ListView>{

	private PullToRefreshListView mListView ;
	private PositionFindAdapter mLiAdapter;
	private String[] sts = new String[]{"促销/导购","传单派发","问卷调查","服务员","钟点工","生活配送","技工","礼仪/模特","司机代驾","家教","翻译","会计","模特","酒吧KTV","礼仪小姐","设计制作","摄像师","实习生","手工制作","网站建设","小时工","学生兼职","其他兼职"};
	private ListView listView__moneycycle = null;
	
	private LinearLayout jzpsn_list_find_apply = null;
	private Map<String, List<ProvinceAndCity>> initData;
	private Myadapter adapterOne;
	private List<ProvinceAndCity> listC;
	private ArrayList<PositionFindEntity>entitys = new ArrayList<PositionFindEntity>();
	private int number =1;//控制页数
	
	private String area;//地区
	private String posi ="2";//控制职位 
	private String cycle ="0";//控制薪资
	private String sort ="ASC";//控制排序
	private int selectNum =0;
	
	private Map<Integer,String> jobIds = new HashMap<Integer, String>();
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.jzposition_list_find);
		
		initView();
		
		initData(area, posi, sort, number, cycle);
	}
	private void initView(){
		initTitle();
		titleTextV.setText("职位检索");
		goBack.setOnClickListener(this);
		initData = ProvinceCity.initData(getResources());
		initDataCity = ProvinceCity.initDataCity(getResources());
		mListView = (PullToRefreshListView) findViewById(R.id.jzpsn_list_find_listView);
		mLiAdapter = new PositionFindAdapter(this);
		mListView.setAdapter(mLiAdapter);
		mListView.setOnItemClickListener(this);
		mListView.setOnRefreshListener(this);
		radioGr = (RadioGroup) findViewById(R.id.radiogroup);
		jzpsn_list_find_apply  = (LinearLayout) findViewById(R.id.jzpsn_list_find_apply);
		jzpsn_list_find_apply.setOnClickListener(this);
		//区域
		RadioButton jzpsn_list_find_area = (RadioButton) findViewById(R.id.jzpsn_list_find_area);
		jzpsn_list_find_area.setOnClickListener(this);
		//职位
		RadioButton jzpsn_list_find_position = (RadioButton) findViewById(R.id.jzpsn_list_find_position);
		jzpsn_list_find_position.setOnClickListener(this);
		//薪资
		RadioButton jzpsn_list_find_money = (RadioButton) findViewById(R.id.jzpsn_list_find_money);
		jzpsn_list_find_money.setOnClickListener(this);
		//排序
		RadioButton jzpsn_list_find_sort = (RadioButton) findViewById(R.id.jzpsn_list_find_sort);
		jzpsn_list_find_sort.setOnClickListener(this);
		
		celect_num = (TextView) findViewById(R.id.jzpsn_list_find__num);
	
	}
	
	private LinearLayout lin;
	private PopupWindow popupWindowTwo;
	private PopupWindow popupWindowThree;
	private PopupWindow popupWindowFour;
	private RadioGroup radioGr;
	private List<String> initDataCity;
	private TextView celect_num;
	
	public void onScrollStateChanged(AbsListView arg0, int arg1) {
	}
	@Override
	public void onClick(View arg0) {
		// TODO Auto-generated method stub
		switch (arg0.getId()) {
		case R.id.jzpsn_list_find_area:
				showPop(radioGr);
			break;
		case R.id.jzpsn_list_find_position:
				showPoptwo(radioGr);
			break;
		case R.id.jzpsn_list_find_money:
				showPopThree(radioGr);
			break;
		case R.id.jzpsn_list_find_sort:
				showPopFour(radioGr);
			break;
		case R.id.title_back:
			onBackPressed();
			break;
		case R.id.jzpsn_list_find_apply:
			StringBuffer sb = new StringBuffer("");
			if(selectNum==0){
				Toast.makeText(this, "请选择您要投递的职位", 0).show();
			}else{
				Iterator iter = jobIds.entrySet().iterator();  
			
				List<String> sts = new ArrayList<String>();
				 while (iter.hasNext()) {  
			            Map.Entry<Integer,String> entry = (Map.Entry<Integer,String>) iter.next();  
			              
			            String value = entry.getValue();  
			            sts.add(value);
			        }  
				
				for(int j=0;j<sts.size();j++){
					if(j==sts.size()-1){
						sb.append(sts.get(j));
					}else{
						sb.append(sts.get(j)+",");
					}
					
				}
				
				
				
			applyJob(sb.toString());
				
			}
			
			break;
		}
	}
	@SuppressWarnings("static-access")
	private void applyJob(String string) {/*
		// TODO Auto-generated method stub
		 RequestParams params = new RequestParams();
	        params.put("access_token",WeiJianZhiEntity.access_token);
	        params.put("jobString",string);
			RequestFactory.getInstance().post("http://182.92.111.126:8084/job/ApplicationJob", params, new AsyncHttpResponseHandler() {
				
				@Override
				public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
					// TODO Auto-generated method stub
					try {
						JSONObject jsonO = new JSONObject(new String(arg2));
						String string2 = jsonO.toString();
						Toast.makeText(getApplicationContext(), string2, 1).show();
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				
				@Override
				public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
					// TODO Auto-generated method stub
					
				}
			});
		
		
		
	*/}
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
	}
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		MobclickAgent.onResume(this);
	}
	@Override
	protected void onPause() {
		super.onPause();
		MobclickAgent.onPause(this);
	}

	private void showPopFour(View v){
		
		View inflate = View.inflate(this, R.layout.tz_sort_layout, null);
		
		ListView listView__order  = (ListView)inflate. findViewById(R.id.jzpsn_list_find__order);
		ArrayList<String> arraylist_order = new ArrayList<String>();
		arraylist_order.add("默认排序");
		arraylist_order.add("薪资金额");
		DialogAdapter adapter_order = new DialogAdapter(PositionListFindActivity.this,arraylist_order);
		listView__order.setAdapter(adapter_order);
		
	   popupWindowFour = new PopupWindow(inflate,LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT,true);  
	        
		   popupWindowFour.setFocusable(true);  
		   popupWindowFour.setOutsideTouchable(true);  
		   popupWindowFour.setBackgroundDrawable(new BitmapDrawable()); 
		   popupWindowFour.setAnimationStyle(R.style.mypopwindow_anim_style);
		   popupWindowFour.showAsDropDown(v);
		   listView__order.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				switch (arg2) {
				case 0:
					sort ="ASC";
					break;
				case 1:
					sort = "DESC";
					break;
				}
				number=1;
				initData(area, posi, sort, arg2, cycle);
			}
		});
		   
		   changeActivity();
		   changeActivity(popupWindowFour);
	}
	
	/**
	 * 职位
	 * @param v
	 */
	private void showPopThree(View v){
		
		View inflate = View.inflate(this, R.layout.tz_salary_layout, null);
		
		listView__moneycycle  = (ListView)inflate. findViewById(R.id.jzpsn_list_find__moneycycle);
		ArrayList<String> arraylist_cycle = new ArrayList<String>();
		arraylist_cycle.add("不限");
		arraylist_cycle.add("日结");
		arraylist_cycle.add("周结");
		arraylist_cycle.add("月结");
		arraylist_cycle.add("完工结算");
		DialogAdapter adapter_cycle = new DialogAdapter(PositionListFindActivity.this,arraylist_cycle);
		listView__moneycycle.setAdapter(adapter_cycle);
		
		popupWindowThree = new PopupWindow(inflate,LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT,true);  
	        
		 popupWindowThree.setFocusable(true);  
		 popupWindowThree.setOutsideTouchable(true);  
		 popupWindowThree.setBackgroundDrawable(new BitmapDrawable()); 
		 popupWindowThree.setAnimationStyle(R.style.mypopwindow_anim_style);
		 popupWindowThree.showAsDropDown(v);
		 listView__moneycycle.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				cycle = arg2+"";
				number=1;
				initData(area, posi, sort, number, cycle);
			}
		});
		 changeActivity();
		 changeActivity(popupWindowThree);
	}
	
	
	//职位
	private void showPoptwo(View v) {
		// TODO Auto-generated method stub
		
		  View inflate = View.inflate(this, R.layout.tz_post_list_layout, null);
		  
		  
		  ListView poptwo_lsit = (ListView) inflate.findViewById(R.id.poptwo_list);
		  
		  
		  poptwo_lsit.setAdapter(new MyadapterPopTwo());
		  
		  poptwo_lsit.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int positi, long id) {
				// TODO Auto-generated method stub
				if(popupWindowTwo!=null &&popupWindowTwo.isShowing()){
					posi =(++positi+"");
					number=1;
					initData(area, posi, sort, positi, cycle);
					popupWindowTwo.dismiss();
				}
			}
		});
		  
		  
		
		 popupWindowTwo = new PopupWindow(inflate,LayoutParams.FILL_PARENT,450,true);  
        
		 popupWindowTwo.setFocusable(true);  
		 popupWindowTwo.setOutsideTouchable(true);  
		 popupWindowTwo.setBackgroundDrawable(new BitmapDrawable()); 
		 popupWindowTwo.setAnimationStyle(R.style.mypopwindow_anim_style);
		 popupWindowTwo.showAsDropDown(v);
		 changeActivity();
		 
		 changeActivity(popupWindowTwo);
      
	}
	//区域
	private void showPop(View v) {
		// TODO Auto-generated method stub
		View inflate = View.inflate(this, R.layout.tz_double_listview_layout, null);
		ListView one_list = (ListView) inflate.findViewById(R.id.one_list);
		final ListView two_list = (ListView) inflate.findViewById(R.id.two_list);
		final PopupWindow   popupWindow = new PopupWindow(inflate,LayoutParams.FILL_PARENT,450,true);  
		changeActivity();
		changeActivity(popupWindow);
        popupWindow.setFocusable(true);  
        popupWindow.setOutsideTouchable(true);  
        popupWindow.setBackgroundDrawable(new BitmapDrawable()); 
        popupWindow.setAnimationStyle(R.style.mypopwindow_anim_style);
        popupWindow.showAsDropDown(v);
            adapterOne = new Myadapter(initDataCity);
            one_list.setAdapter(adapterOne);
        one_list.setOnItemClickListener(new OnItemClickListener() {


			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				 new Myadapter(initDataCity);
				adapterOne.seletePosition(position);
				String string = ((TextView)view).getText().toString();
				listC = initData.get(string);
				
				MyadapterTwo mAdapterTwo = new MyadapterTwo(listC);
				two_list.setAdapter(mAdapterTwo);
			}
		});
        
        two_list.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int positi, long id) {
				// TODO Auto-generated method stub
				 ProvinceAndCity provinceAndCity = listC.get(positi);
				 area=provinceAndCity.id;
				 number=1;
				 initData(area, posi, sort, positi, cycle);
				 
				 popupWindow.dismiss();
			}
		});
        
	}
	
	private class Myadapter extends BaseAdapter{

		 private List<String>strings;
		 private int posi = 100;
		public Myadapter(List<String> lists){
			this.strings = lists;
		}
		
       
       public void seletePosition(int po){
    	   
    	   this.posi = po;
    	   notifyDataSetChanged();
       }
		@Override
		public int getCount() {
			// TODO Auto-generated method stub
				return strings.size();
			
		}

		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public View getView(int arg0, View arg1, ViewGroup arg2) {
			// TODO Auto-generated method stub
			
			
			TextView tv = new TextView(PositionListFindActivity.this);
				if(arg0==posi){
					tv.setTextColor(getResources().getColor(R.color.red));
				}else{
					tv.setTextColor(getResources().getColor(R.color.black));
				}
				tv.setText(strings.get(arg0));
				
				tv.setPadding(20, 15, 0, 15);
			
			return tv;
		}
		
	}
	private class MyadapterTwo extends BaseAdapter{
		
		private List<ProvinceAndCity> ens;
		
		public MyadapterTwo(List<ProvinceAndCity> entitys){
			
			this.ens = entitys;
		}
		
		@Override
		public int getCount() {
			// TODO Auto-generated method stub
				return ens.size();
			
		}
		
		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return null;
		}
		
		@Override
		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return 0;
		}
		
		@Override
		public View getView(int arg0, View arg1, ViewGroup arg2) {
			// TODO Auto-generated method stub
			
			
			TextView tv = new TextView(PositionListFindActivity.this);
			tv.setTextColor(getResources().getColor(R.color.black));
				ProvinceAndCity provinceAndCity = ens.get(arg0);
				tv.setText(provinceAndCity.name);
				tv.setPadding(20, 15, 0, 15);
			return tv;
		}
		
	}
	private class MyadapterPopTwo extends BaseAdapter{
		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return sts.length;
			
		}
		
		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return null;
		}
		
		@Override
		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return 0;
		}
		
		@Override
		public View getView(int arg0, View arg1, ViewGroup arg2) {
			// TODO Auto-generated method stub
			
			TextView tv = new TextView(PositionListFindActivity.this);
			tv.setTextColor(getResources().getColor(R.color.black));
			tv.setText(sts[arg0]);
			tv.setPadding(20, 15, 0, 15);
			return tv;
		}
		
	}
	/**
	 * 设置屏幕变暗
	 */
	public void changeActivity(){
		WindowManager.LayoutParams params = getWindow().getAttributes();
		params.alpha = 0.7f;
		getWindow().setAttributes(params);
		
		
	}
	/**
	 * 回复屏幕
	 */
	public void changeActivity(PopupWindow pop){
		pop.setOnDismissListener(new OnDismissListener() {
			
			@Override
			public void onDismiss() {
				// TODO Auto-generated method stub
				WindowManager.LayoutParams params = getWindow().getAttributes();
				params.alpha = 1f;
				getWindow().setAttributes(params);
			}
		});

		
	}
	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
		// TODO Auto-generated method stub
		number=1;
		initData(area, posi, sort, number, cycle);
	}
	@Override
	public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
		// TODO Auto-generated method stub
		number++;
		initData(area, posi, sort, number, cycle);
	}
	
	@SuppressWarnings("static-access")
	public void initData(String area,String posi,String sort,final int number,String cycle){/*
		client_id 必须
		client_secret 必须
		area 地区.
		position 分类.
		bonus_cycle 结算方式.
		order 排序字段.
		direction 排序方向 默认倒叙 ASC 正序 DESC 倒叙..
		page 页数
		limit 每页条数.
		
		 RequestParams params = new RequestParams();
        params.put("client_id","android");
        params.put("client_secret","61bcd762eaa9f3b2a891f33661ddaf42");
        if(!"0".equals(area)){
        	params.put("area", area);
        } 
        params.put("bonus_cycle",cycle);
        params.put("position",posi);
        params.put("order", "bonus");
        params.put("direction",sort);
        params.put("limit", "10");
        params.put("page", ""+number);
		RequestFactory.getInstance().get("http://182.92.111.126:8084/job/GetJobListByOption", params, new AsyncHttpResponseHandler() {

			@Override
			public void onFailure(int arg0, Header[] arg1, byte[] arg2,
					Throwable arg3) {
				
			}

			@Override
			public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
				// TODO Auto-generated method stub
				
				try {
					JSONObject jsonO = new JSONObject(new String(arg2));
					if(jsonO.optBoolean("status")){
						
						if(1==number)entitys.clear();
						
						JSONArray jsonA = jsonO.optJSONArray("data");
						for(int j=0;j<jsonA.length();j++){
							JSONObject json= jsonA.optJSONObject(j);
							PositionFindEntity entity = new PositionFindEntity();
							entity.id = json.optString("id");
							entity.title = json.optString("title");
							entity.area = json.optString("area");
							entity.company_name = json.optString("company_name");
							entity.company_id = json.optString("company_id");
							entity.deadline = json.optString("deadline");
							entity.bonus = json.optString("bonus");
							entity.bonus_type = json.optString("bonus_type");
							entity.position = json.optString("position");
							entitys.add(entity);
						}
						mLiAdapter.onBoundData(entitys);
					}else{
						String error = jsonO.optString("errMessage");
						Toast.makeText(Position_list_find.this, error, 0).show();
					}
					
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}
		@Override
		public void onFinish() {
			// TODO Auto-generated method stub
			super.onFinish();
			mListView.onRefreshComplete();
		}
		
		
		});
			
		
	*/}
	public class PositionFindAdapter extends SimpleBaseAdapter<PositionFindEntity> {

		public PositionFindAdapter(Context context) {
			super(context);
			// TODO Auto-generated constructor stub
		}

		@Override
		public int getItemResource() {
			// TODO Auto-generated method stub
			return R.layout.jzposition_list_find_item;
		}

		@Override
		public View getItemView(final int position, View convertView,
				com.guangzhi.weijianzhi.adapter.SimpleBaseAdapter.ViewHolder holder) {
			
		final PositionFindEntity entity = datas.get(position);
			TextView title = (TextView) holder.getView(R.id.jzpsn_list_find_item_title);
			
			title.setText(entity.title);
			
			TextView area = (TextView) holder.getView(R.id.jzpsn_list_find_item_area);
			title.setText(entity.area);
			
			TextView company = (TextView) holder.getView(R.id.jzpsn_list_find_item_company);
			company.setText(entity.company_name);
			
			TextView lastday = (TextView) holder.getView(R.id.jzpsn_list_find_item_lastday);
			lastday.setText(entity.deadline);
			
			ImageView tui_ding = (ImageView) holder.getView(R.id.jzpsn_list_find_tui_item_ding);
			
			CheckBox checkBox = (CheckBox) holder.getView(R.id.jzpsn_list_find_item_checkBox);
			
			
			checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
				
				@Override
				public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
					// TODO Auto-generated method stub
					entity.isSelect = isChecked;
					if(isChecked){
						++selectNum;
						jobIds.put(position, entity.id);
					}else{
						--selectNum;
						jobIds.remove(position);
					}
					celect_num.setText(selectNum+"");
				}
			});
			
			checkBox.setChecked(entity.isSelect);
			if("1".equals(entity.bonus_type)){
				tui_ding.setImageResource(R.drawable.gz_income_push);
			}else if("2".equals(entity.bonus_type)){
				tui_ding.setImageResource(R.drawable.gz_income_ding);
			}else{
				tui_ding.setVisibility(View.GONE);
			}
			
			
			return convertView;
		}

	}
}
